package com.yklx.youke.service;

import com.yklx.youke.entity.Session;
import com.yklx.youke.entity.Teacher;
import com.yklx.youke.repository.SessionRepository;
import com.yklx.youke.repository.TeacherRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class SessionService {

    private final SessionRepository sessionRepository;
    private final TeacherRepository teacherRepository;

    public SessionService(SessionRepository sessionRepository, TeacherRepository teacherRepository) {
        this.sessionRepository = sessionRepository;
        this.teacherRepository = teacherRepository;
    }

    public List<Map<String, Object>> getAvailableTimeSlots(UUID teacherId, String subject, LocalDate startDate, LocalDate endDate) {
        // Get the teacher with their availability
        Teacher teacher = teacherRepository.findById(teacherId)
                .orElseThrow(() -> new IllegalArgumentException("Teacher not found: " + teacherId));

        // Parse the availability JSON to get available times
        // This would parse the availability string from the Teacher entity
        // For now, we'll return a placeholder implementation
        
        // In a real implementation, this would parse the JSON availability data
        // and compare with existing booked sessions to find available slots
        return List.of(
            Map.of(
                "date", startDate,
                "slots", new String[]{"09:00-10:00", "14:00-15:00", "16:00-17:00"}
            ),
            Map.of(
                "date", startDate.plusDays(1),
                "slots", new String[]{"10:00-11:00", "15:00-16:00"}
            )
        );
    }

    public Map<String, Object> startSession(UUID sessionId) {
        Session session = sessionRepository.findById(sessionId)
                .orElseThrow(() -> new IllegalArgumentException("Session not found: " + sessionId));

        // Update session status to IN_PROGRESS
        session.setStatus(Session.SessionStatus.IN_PROGRESS);
        Session updatedSession = sessionRepository.save(session);

        // In a real implementation, this would also trigger room creation and notifications

        return Map.of(
            "session", updatedSession,
            "classroom", Map.of(
                "roomUrl", "https://example.com/classroom/" + sessionId,
                "accessInfo", "Access code: " + generateAccessCode()
            )
        );
    }

    public Map<String, Object> completeSession(UUID sessionId, String feedback, Integer rating) {
        Session session = sessionRepository.findById(sessionId)
                .orElseThrow(() -> new IllegalArgumentException("Session not found: " + sessionId));

        // Update session information
        session.setStudentFeedback(feedback);
        session.setRating(rating);
        session.setStatus(Session.SessionStatus.COMPLETED);
        
        Session updatedSession = sessionRepository.save(session);

        // In a real implementation, this would also process payments and trigger notifications

        return Map.of(
            "session", updatedSession,
            "paymentProcessed", true
        );
    }

    // 获取所有会话/排课
    public List<Session> getAllSessions() {
        return sessionRepository.findAll();
    }

    // 根据ID获取会话/排课
    public Session getSessionById(UUID sessionId) {
        return sessionRepository.findById(sessionId).orElse(null);
    }

    // 创建新会话/排课
    public boolean createSession(Session session) {
        try {
            sessionRepository.save(session);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 更新会话/排课
    public boolean updateSession(Session session) {
        try {
            if (getSessionById(session.getSessionId()) != null) {
                sessionRepository.save(session);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 删除会话/排课
    public boolean deleteSession(UUID sessionId) {
        try {
            if (getSessionById(sessionId) != null) {
                sessionRepository.deleteById(sessionId);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private String generateAccessCode() {
        // Generate a random access code
        return String.valueOf((int)(Math.random() * 9000) + 1000); // 4-digit code
    }
}